﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VietThinks.Website.Controllers;
using VietThinks.Web.Mvc;

namespace VietThinks.Website.ActionFilter
{
    public class IgnoreSearchEngineFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext.Request;
            
            if (!IsSearchEngine(request))
            {
                base.OnActionExecuting(filterContext);
                return;
            }

            string absoluteUri = request.Url.AbsoluteUri;
            var urlHelper = new UrlHelper(filterContext.RequestContext);
            filterContext.Result = new RedirectResult(urlHelper.ActionEx<ErrorController>(c => c.Forbidden(absoluteUri)));
        }

        protected bool IsSearchEngine(HttpRequestBase request)
        {
            var searchEngines = GetSearchEngineList();

            return searchEngines.Any(se => request.UserAgent.Contains(se));
        }

        protected IList<string> GetSearchEngineList()
        {
            string ignoredBotList = ConfigurationManager.AppSettings["IgnoredBotList"];

             return CacheManager.Get<List<string>>(CachingKey.IgnoredBotList.ToString(),
                        () =>
                        {
                            return ignoredBotList != null
                                        ? ignoredBotList.Split(',')
                                            .Where(s => !String.IsNullOrEmpty(s.Trim()))
                                            .Select(s => s.Trim())
                                            .ToList()
                                        : new List<string>();                            
                        },
                        Repository.Memory);
        }
    }
}
